﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OAclient.Models;
using System.IO;
using System.Xml.Linq;
using CommonLibrary.DataModel.Form;
using ServiceApplication.Service;
using CommonLibrary.Common;
using ServiceApplication.Service.Basic;
using System.Xml;
using OAclient.Common;
using System.Data;
using CommonLibrary.DataModel.Basic;
using OAclient.Filters;
using SedionFormDesigner;

namespace OAclient.Controllers
{
    [VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class FormController : Controller
    {
        FormService formService = new FormService();
        SerializeDesigner designer = new SerializeDesigner();
        BasicService basicService = new BasicService();
        private SedinFormSerializeManager serializeManager = new SedinFormSerializeManager();

        private const Int32 PageSize = 15;

        public ActionResult FormList(UserModel user, Int32 page)
        {
            var dt_forms = formService.QueryFormDataTable(-1);
            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = dt_forms.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt_forms.Rows.Count > 0)
                dt_forms = dt_forms.AsEnumerable().Skip((page - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt_forms"] = dt_forms;
            return PartialView();
        }

        //显示表单
        public ActionResult FormShow(int form_id)
        {
            string formdefine = string.Empty;
            FormEntity formEntity = formService.QueryFormEntity(form_id);
            UserEntity user = basicService.QueryUser(22);
            StaffEntity se = basicService.QueryStaff(user.staff_id);
            DeptEntity dept = basicService.QueryDept(se.dept_id);
            DutyEntity duty = basicService.QueryDuty(se.duty_id);
            DataTable dt_duty = basicService.QueryAllDutys();
            string[] arr_allduty = dt_duty.AsEnumerable().Select(x => x["职位名称"].ToString()).ToArray();

            if (formEntity != null)
            {
                XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));

                //返回
                //formdefine = designer.DeserializeXmlToWeb(xml, new SerializeAutoData(true) { user_name = user.user_name, user_deptname = dept.dept_name, user_dutyname = duty.duty_name, user_id = user.user_id.ToString(), ComboAllDutyList = arr_allduty });

                formdefine = serializeManager.SerializeXmlToHtml(xml);
            }
            ViewData["formdefi"] = formdefine;
            return PartialView();
        }

        public ActionResult FormUpload()
        {
            return PartialView();
        }


        #region 调用方法
        //上传表单文件
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload(HttpPostedFileBase fileData, UserModel user)
        {
            //HttpPostedFileBase file1 = Request.Files["fileData"];

            //string result = string.Empty;
            if (null != fileData)
            {
                try
                {
                    //保存到文件
                    string filename = Path.GetFileName(fileData.FileName);//获得文件名
                    string ext = Path.GetExtension(fileData.FileName);//获得文件扩展名
                    if (!ext.Equals(".rar", StringComparison.CurrentCultureIgnoreCase))
                    {
                        return Content("请上传压缩包类型文件");
                    }

                    string filepath = Server.MapPath("~/UploadFiles/Form/");
                    FormEntity formEntity = null;
                    if (!Directory.Exists(filepath))
                    {
                        Directory.CreateDirectory(filepath);
                    }
                    String fileNameWithoutExten = Path.GetFileNameWithoutExtension(filename);
                    Boolean dirExist;
                    dirExist = Directory.Exists(Path.Combine(filepath, fileNameWithoutExten));
                    //FileInfo f = new FileInfo(filepath + filename);

                    ZipHelper zipHelper = new ZipHelper();
                    //如果存在，则自动更新文件
                    if (dirExist)
                    {
                        //f.Delete();
                        //Directory.Delete(Path.Combine(filepath, fileNameWithoutExten), true);
                        //System.Threading.Thread.Sleep(500);
                        fileData.SaveAs(Path.Combine(filepath, filename));

                        // 解压压缩包
                        zipHelper.DecompressFile(Path.Combine(filepath, filename));

                        XElement xml = XElement.Load(Path.Combine(filepath + fileNameWithoutExten, fileNameWithoutExten + ".xml"));
                        //result = designer.DeserializeXmlToWeb(xml, null);
                    }
                    else
                    {
                        fileData.SaveAs(Path.Combine(filepath, filename));

                        // 解压压缩包
                        zipHelper.DecompressFile(Path.Combine(filepath, filename));

                        XElement xml = XElement.Load(Path.Combine(filepath + fileNameWithoutExten, fileNameWithoutExten + ".xml"));

                        //保存到数据库
                        //result = designer.DeserializeXmlToWeb(xml, null);
                        formEntity = serializeManager.SerializeXmlToFormEntity(xml);
                        formEntity.user_name = user.user.user_name;
                        formEntity.catalogy = "";
                        formEntity.createtime = DateTime.Now.ToString();
                        formEntity.dept_id = -1;
                        formEntity.descn = "";
                        formEntity.lasttime = DateTime.Now.ToString();
                        formEntity.location = fileNameWithoutExten + "/" + fileNameWithoutExten + ".xml";
                        formEntity.user_id = user.user.user_id;
                        formEntity = formService.AddForm(formEntity);
                    }
                }
                catch (Exception e)
                {
                    return Content("上传失败:" + e.Message);
                }
            }
            return Content("上传成功");
        }

        public String QueryTable(String txtValue, String sqlValue)
        {
            String table = String.Empty;
            if (txtValue != String.Empty)
            {
                txtValue = txtValue.Replace("\n", "");
                var strs = CommonMethod.splitString(txtValue);
                if (strs.Count() == 0)
                    return "wrong";
                table = designer.GetTableWithData(strs, sqlValue);
            }
            return table;
        }

        #endregion
    }
}
